#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2020/10/16 9:11
# @Author  : Wang Feng
# @FileName: utils.py
# @Software: PyCharm
import hashlib
import re

import six

"""
uiautomation_parser的工具类
"""


def escape_name(name):
    if six.PY2:
        try:
            name.decode('string_escape').encode('unicode_escape')
        except UnicodeDecodeError:
            return name.decode('string_escape').decode('utf-8')
    return name.encode('ascii', 'backslashreplace').decode('unicode_escape')


def md5(*args):
    m = hashlib.md5()
    for arg in args:
        part = arg.encode('utf-8')
        m.update(part)
    return m.hexdigest()


def uiautomation_package(case_relpath):
    # '基础服务\\用户登陆\\test_carrier_login.py'
    path = case_relpath.rsplit('.', 1)[0]
    return path.replace('\\', '.')


def uiautomation_full_name(package, clazz, test):
    full_name = '{package}.{clazz}#{test}'.format(package=package, clazz=clazz, test=test)
    return escape_name(full_name)


def parse_comments(comments):
    """
    解析注释信息
    :param comments:
    :return: 信息字典{'创建时间': '2020/09/15 09:59', '责任人': '汪峰'}
    """
    if comments is None:
        return {'create_time': None, 'author': None}
    comments = list(filter(lambda comment: '@Time' in comment or '@Author' in comment, comments.split('\n')))
    comments = list(map(lambda x: x.split(' :'), comments))
    test_case_msg = dict()
    for k, v in comments:
        if '@Time' in k:
            test_case_msg['create_time'] = v.strip()
        elif '@Author' in k:
            test_case_msg['author'] = v.strip()
    return test_case_msg


def get_code_config(source_code):
    code_config = dict()
    result = re.search(
        r'\n@allure.epic\("(.+)"\)(.*\n)+@allure.feature\("(.+)"\)(.*\n)+\s+@allure.story\("(.+)"\)(.*\n)+\s+@allure.title\("(.+)"\)',
        source_code)
    code_config['epic'] = result.group(1)
    code_config['feature'] = result.group(3)
    code_config['story'] = result.group(5)
    code_config['title'] = result.group(7)
    result = re.findall(r'\n+\s+@pytest.mark.(.+)', source_code)
    # if 'test' in result:
    #     code_config['test'] = True
    # if 'pro' in result:
    #     code_config['pro'] = True
    # if 'core' in result:
    #     code_config['core'] = True
    if len(result) == 1:
        code_config['marks'] = result[0]
    elif len(result) > 1:
        code_config['marks'] = ','.join(result)
    else:
        code_config['marks'] = ''
    return code_config


if __name__ == '__main__':
    path = '基础服务\\用户登陆\\test_carrier_login.py'.rsplit('.', 1)[0]
    # print(path.replace('\\', '.'))
    # print(uiautomation_full_name(uiautomation_package('基础服务\\用户登陆\\test_carrier_login.py'), 'a', 'b'))

    source_code = """import allure
import pytest
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))
from page.recruit_list_page import RecruitListPage
from utils.jmeterUtils import JmeterUtils
import module.globals as gbl


@allure.epic("军民融合")
@allure.feature("运营管理")
class TestSelectRecruitCombination(object):

    def setup(self):
        self.driver = gbl.driver
        self.data = gbl.data
        self.data['project_name'] = 'UI' + str(int(round(time.time() * 1000000)))
        JmeterUtils.exec('UI测试数据.jmx', '发布需求-直接采购', '-JgoodsName=' + self.data['project_name'])

    def teardown(self):
        gbl.db.execute_query("DELETE FROM `atms_order_whole_car` WHERE `goods_name` = '{project_name}'"
                             .format(project_name=self.data['project_name']))
        self.driver.get(gbl.data['host'] + '/recruit')

    @allure.story("招募管理")
    @allure.title("招募列表组合筛选")
    @pytest.mark.test
    @pytest.mark.pro
    def test_select_recruit_combination(self): 
        with allure.step("步骤：1.输入招募状态为'待响应'"):
            RecruitListPage(self.driver).select_combobox(title='招募状态', value='待响应')

        with allure.step("步骤：2.输入计划用车"):
            start_date = datetime.date.today().strftime('%Y{y}%#m{m}%#d{d}') \
                .format(y='年', m='月', d='日')
            end_date = (datetime.date.today() + datetime.timedelta(4)).strftime('%Y{y}%#m{m}%#d{d}') \
                .format(y='年', m='月', d='日')
            RecruitListPage(self.driver).set_calendar_range('计划用车', start_date, end_date)

        with allure.step("步骤：3.输入需求发布时间"):
            start_date = datetime.date.today().strftime('%Y{y}%#m{m}%#d{d}') \
                .format(y='年', m='月', d='日')
            end_date = (datetime.date.today() + datetime.timedelta(1)).strftime('%Y{y}%#m{m}%#d{d}') \
                .format(y='年', m='月', d='日')
            RecruitListPage(self.driver).set_calendar_range('需求发布时间', start_date, end_date)

        with allure.step("步骤：4.输入关键字"):
            RecruitListPage(self.driver).type_keywords(title='关键词', value=self.data['project_name'])

        with allure.step("步骤：5.点击查询"):
            RecruitListPage(self.driver).click_button('查 询')
            time.sleep(0.5)

        with allure.step("预期：数据展示正确，各项数据匹配"):
            rows_num = RecruitListPage(self.driver).get_rows_num()
            assert 1 == rows_num
            data = {'任务代号': self.data['project_name'], '招募状态': '待响应', '需求方': 'UIREQUIREMENT',
                    '采购方式': '直采', '需求车辆': '5.2米平板车/1车次', '计划用车': str(datetime.date.today()), '完成度': '0'}
            assert RecruitListPage(self.driver).is_exist_data(data)

        with allure.step("步骤：6.点击重置"):
            RecruitListPage(self.driver).click_button('重 置')
            time.sleep(0.5)

        with allure.step("预期：数据重置成功"):
            rows_num = RecruitListPage(self.driver).get_rows_num()
            assert 20 == rows_num
    """
    print(get_code_config(source_code))
